package cn.edu.nju.ws.sview.wyge.servlets;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.URIIDCache;
import cn.edu.nju.ws.sview.rdf.Resource;
import cn.edu.nju.ws.sview.wyge.relations.adataset.BasicTriplePattern;
import cn.edu.nju.ws.sview.wyge.relations.adataset.CustomDataset;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.Relation;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.Relations;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.qxliu.relation.RelationEvaluation;
import cn.edu.nju.ws.sview.wyge.relations.datasets.DatasetItem;
import cn.edu.nju.ws.sview.wyge.util.Util;

/**
 * Servlet implementation class Entity
 */
public class RelationOriginal extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RelationOriginal() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String json = null;
		response.setCharacterEncoding("utf-8");
		if (request.getParameter("original") != null) {
			json = request.getParameter("original");
			String str = URLDecoder.decode(json, "UTF-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			int start = ((Long) regtJSON.get("start")).intValue();
			int length = ((Long) regtJSON.get("length")).intValue();
			String ds_type = (String) regtJSON.get("ds_type");
			String idStr = (String) regtJSON.get("idStr");
			int ds_id = Integer.parseInt((String) regtJSON.get("ds_id"));
			String user = (String) regtJSON.get("user");
			String lang = (String) regtJSON.get("lang");
			
			ArrayList<Integer> docs = new ArrayList<Integer>();
			if(ds_type.contentEquals(DatasetItem.TEMP_GENRE)){
				String[] strList = idStr.split("_");
				for(String id :strList){
					if(id.trim().length()>0){
						docs.add(Integer.parseInt(id));
					}
				}
			}else if (ds_type.equals(DatasetItem.URI_GENRE)) {
				docs.add(ds_id);
			} else if (ds_type.equals(DatasetItem.CUSTOM_GENRE)) {
				docs.addAll(CustomDataset.getURLIDsByCustomDatasetId(ds_id));
			}
			List<ArrayList<String>> originals = new BasicTriplePattern(docs).getAll(start, length);

			int totalNum = 0;
			totalNum = new BasicTriplePattern(docs).getTotalNum();
//			ArrayList<Relation> array = Relations.getOriginal(ds_type, ds_id,
//					user, start, length, lang);

			try {
			JSONArray elements = new JSONArray();
			for (ArrayList<String> row : originals) {
				String name = null;
				int id = -1;
				String uri = null;
				String roles = "";
				String type = null;
				if(row.get(1).contentEquals("uhttp://www.w3.org/1999/02/22-rdf-syntax-ns#type")){
					type = "class";
					name = Util.getLocalname(row.get(2));
					uri =  row.get(2);//"uhttp://..."
					id = URIIDCache.getInstance().getURIID(uri.substring(1), false);
					roles = row.get(0);
				}else{
					type = "property";
					name = Util.getLocalname(row.get(1));
					uri = row.get(1);//"uhttp://..."
					id = URIIDCache.getInstance().getURIID(uri.substring(1), false);
					roles = row.get(0)+","+row.get(2);
				}
				JSONObject jsob = new JSONObject();
				jsob.put("type", type);
				jsob.put("id", id);
				jsob.put("name", name);
				jsob.put("uri", uri);
//				jsob.put("group", item.getGroup());
//				jsob.put("time", item.getDate());
//				jsob.put("lang", item.getLang());
				if(roles.length()<=0){
					System.err.println("Error in RelationOriginal.java!  item:"+row.toString());
				}else{
					jsob.put("roles", roles);
					elements.add(jsob);
				}
			}
			JSONObject result = new JSONObject();
//			System.out.println("elems:"+elements.toJSONString());
			result.put("result", elements);
			result.put("totalNum", totalNum);
			response.getWriter().print(result);
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(request.getParameter("getResult") != null){
			json = request.getParameter("getResult");
			String str = URLDecoder.decode(json, "UTF-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String ds_type = (String) regtJSON.get("ds_type");
			String idStr = (String) regtJSON.get("idStr");
			int ds_id = Integer.parseInt((String) regtJSON.get("ds_id"));
			String[] roles = ((String) regtJSON.get("roles")).split(",");
			String uri = (String) regtJSON.get("uri");
			String type = (String) regtJSON.get("type");
			ArrayList<String[]> in = new ArrayList<String[]>();
			String[] row = new String[3];
			if(type.contentEquals("class")){
				row[0] = roles[0];
				row[1] = "uhttp://www.w3.org/1999/02/22-rdf-syntax-ns#type";
				row[2] = uri;
			}else if(type.contentEquals("property")){
				row[0] = roles[0];
				row[1] = uri;
				row[2] = roles[1];
			}
			in.add(row);
			
			ArrayList<Integer> docs = new ArrayList<Integer>();
			if(ds_type.contentEquals(DatasetItem.TEMP_GENRE)){
				String[] strList = idStr.split("_");
				for(String id :strList){
					if(id.trim().length()>0){
						docs.add(Integer.parseInt(id));
					}
				}
			}else if (ds_type.equals("uri")) {
				docs.add(ds_id);
			} else if (ds_type.equals("custom")) {
				docs.addAll(CustomDataset.getURLIDsByCustomDatasetId(ds_id));
			}
			RelationEvaluation releval = new RelationEvaluation();
			ArrayList<ArrayList<String>> vals = releval.getValuesFromPatterns(in, docs);
			JSONArray elements = new JSONArray();
			
			ArrayList<String> tableHead = vals.get(0);
			JSONArray jsary = new JSONArray();
			for (String h : tableHead) {
				JSONObject jsob = new JSONObject();
				jsob.put("v", h);
				jsob.put("vname", h);
				jsary.add(jsob);	
			}
			elements.add(jsary);

			for (int i = 1; i < vals.size(); i++) {
				JSONArray jsar = new JSONArray();
				ArrayList<String> valRow = vals.get(i);
				for (int j = 0; j < tableHead.size(); j++) {
					JSONObject jsob = new JSONObject();
					String v = tableHead.get(j);
					String code = valRow.get(j);
					String name = RelationResult.getName(code);
					String content = RelationResult.getContent(code);
					String displayName = RelationResult.getDisplayName(code);
					jsob.put("v", v);
					jsob.put("name", name);
					jsob.put("content", content);
//					jsob.put("code", code);
					jsob.put("displayName", displayName);
					if(code.startsWith("u")){
						try {
							jsob.put("uri_id", URIIDCache.getInstance().getURIID(code.substring(1), false));
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Throwable e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
					jsar.add(jsob);	
				}
				elements.add(jsar);
			}
			JSONObject result = new JSONObject();
			result.put("result", elements);
			response.getWriter().print(result);
		}else if(request.getParameter("originalNum") != null){
			json = request.getParameter("originalNum");
			String str = URLDecoder.decode(json, "UTF-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
//			int start = ((Long) regtJSON.get("start")).intValue();
//			int length = ((Long) regtJSON.get("length")).intValue();
			String ds_type = (String) regtJSON.get("ds_type");
			String idStr = (String) regtJSON.get("idStr");
			int ds_id = Integer.parseInt((String) regtJSON.get("ds_id"));
//			String user = (String) regtJSON.get("user");
			String lang = (String) regtJSON.get("lang");
			
			ArrayList<Integer> docs = new ArrayList<Integer>();
			if(ds_type.contentEquals(DatasetItem.TEMP_GENRE)){
				String[] strList = idStr.split("_");
				for(String id :strList){
					if(id.trim().length()>0){
						docs.add(Integer.parseInt(id));
					}
				}
			}else if (ds_type.equals("uri")) {
				docs.add(ds_id);
			} else if (ds_type.equals("custom")) {
				docs.addAll(CustomDataset.getURLIDsByCustomDatasetId(ds_id));
			}

			int totalNum = 0;
			totalNum = new BasicTriplePattern(docs).getTotalNum();
			JSONObject result = new JSONObject();
			result.put("totalNum", totalNum);
			response.getWriter().print(result);
		}else if(request.getParameter("objectOriginalNum") != null){
			json = request.getParameter("objectOriginalNum");
			String str = URLDecoder.decode(json, "UTF-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
//			int start = ((Long) regtJSON.get("start")).intValue();
//			int length = ((Long) regtJSON.get("length")).intValue();
			String ds_type = (String) regtJSON.get("ds_type");
			String idStr = (String)regtJSON.get("idStr");
			int ds_id = Integer.parseInt((String) regtJSON.get("ds_id"));
//			String user = (String) regtJSON.get("user");
			String lang = (String) regtJSON.get("lang");
			
			ArrayList<Integer> docs = new ArrayList<Integer>();
			if(ds_type.contentEquals(DatasetItem.TEMP_GENRE)){
				String[] strList = idStr.split("_");
				for(String id :strList){
					if(id.trim().length()>0){
						docs.add(Integer.parseInt(id));
					}
				}
			}else if (ds_type.equals("uri")) {
				docs.add(ds_id);
			} else if (ds_type.equals("custom")) {
				docs.addAll(CustomDataset.getURLIDsByCustomDatasetId(ds_id));
			}

			int totalNum = 0;
			totalNum = new BasicTriplePattern(docs).getObjectPropNum();
//			System.out.println("ttn:"+totalNum);
			
			JSONObject result = new JSONObject();
			result.put("totalNum", totalNum);
			response.getWriter().print(result);
		}else if(request.getParameter("objectOriginal") != null){
			json = request.getParameter("objectOriginal");
			String str = URLDecoder.decode(json, "UTF-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			int start = ((Long) regtJSON.get("start")).intValue();
			int length = ((Long) regtJSON.get("length")).intValue();
			String ds_type = (String) regtJSON.get("ds_type");
			String idStr = (String) regtJSON.get("idStr");
			int ds_id = Integer.parseInt((String) regtJSON.get("ds_id"));
			String user = (String) regtJSON.get("user");
			String lang = (String) regtJSON.get("lang");
			
			ArrayList<Integer> docs = new ArrayList<Integer>();
			if(ds_type.contentEquals(DatasetItem.TEMP_GENRE)){
				String[] strList = idStr.split("_");
				for(String id :strList){
					if(id.trim().length()>0){
						docs.add(Integer.parseInt(id));
					}
				}
			}else if (ds_type.equals("uri")) {
				docs.add(ds_id);
			} else if (ds_type.equals("custom")) {
				docs.addAll(CustomDataset.getURLIDsByCustomDatasetId(ds_id));
			}
			List<ArrayList<String>> originals = new BasicTriplePattern(docs).getObjectProp(start, length);//.getAll(start, length);

			int totalNum = 0;
			totalNum = new BasicTriplePattern(docs).getObjectPropNum();
//			ArrayList<Relation> array = Relations.getOriginal(ds_type, ds_id,
//					user, start, length, lang);

			try {
			JSONArray elements = new JSONArray();
			for (ArrayList<String> row : originals) {
				String name = null;
				int id = -1;
				String uri = null;
				String roles = "";
				String type = null;
//				if(row.get(1).contentEquals("uhttp://www.w3.org/1999/02/22-rdf-syntax-ns#type")){
//					type = "class";
//					name = Util.getLocalname(row.get(2));
//					uri =  row.get(2);//"uhttp://..."
//					id = URIIDCache.getInstance().getURIID(uri.substring(1), false);
//					roles = row.get(0);
//				}else{
					type = "property";
					name = Util.getLocalname(row.get(1));
					uri = row.get(1);//"uhttp://..."
					id = URIIDCache.getInstance().getURIID(uri.substring(1), false);
					roles = row.get(0)+","+row.get(2);
//				}
				JSONObject jsob = new JSONObject();
				jsob.put("type", type);
				jsob.put("id", id);
				jsob.put("name", name);
				jsob.put("uri", uri);
//				jsob.put("group", item.getGroup());
//				jsob.put("time", item.getDate());
//				jsob.put("lang", item.getLang());
				if(roles.length()<=0){
					System.err.println("Error in RelationOriginal.java!  item:"+row.toString());
				}else{
					jsob.put("roles", roles);
					elements.add(jsob);
				}
			}
			JSONObject result = new JSONObject();
//			System.out.println("elems:"+elements.toJSONString());
			result.put("result", elements);
			result.put("totalNum", totalNum);
//			System.out.println("obj:"+result.toJSONString());
			response.getWriter().print(result);
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
